package com.baizhi.service.impl;

import com.baizhi.dao.UserDao;
import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    // 由于是查询，只需要支持事务就可以了
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public User login(User user) {
        User userDB = userDao.findByName(user.getName());
        if (userDB!=null) {
            if (StringUtils.equals(userDB.getPassword(), user.getPassword())) {
                return userDB;
            }
            throw new RuntimeException("密码输入错误");
        }
        throw new RuntimeException("用户名输入错误");
    }

    // 用户注册的校验
    @Override
    public void register(User user) {
        User userDB = userDao.findByName(user.getName());
        if (userDB!=null) {
            throw new RuntimeException("当前用户名已被注册，请修改后再试！");
        }
        user.setRegtime(new Date());
        user.setStatus("激活");
        userDao.save(user);
    }


}
